package clientMain;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import objectView.UserAuthorization;
import utility.MD5;
import utility.StringUtil;
import utility.UtilDelegate;
import xml.XMLProcess;
import clientUtilGUI.UtilityGUI;
import database.UserDelegate;

public class Login extends JFrame implements ActionListener{
	
    public static Connection conn;
    private static String server;
    private static String port;
    
    int screenHeight = UtilityGUI.screenSize.height;
	int screenWidth = UtilityGUI.screenSize.width;
    int width = 280;
	int heightMin = 250;
	int heightMax = 300;
    
    private JTextField txtUserName;
    private JPasswordField txtUserPass;
	private JCheckBox cbPass;
	private JPanel panelBtn;
	private JButton btnLogin;
	private JButton btnCancel;
	private JLabel lblTitle;
	private JCheckBox cbConfig;
	private JLabel lblUserName;
	private JLabel lblUserPass;
	
	private JPanel panelConfig;
	private GridBagConstraints gbc_panelConfig;
	private JLabel lblServer;
	private JTextField txtServer;
	private JLabel lblPort;
	private JTextField txtPort;
	private JButton btnLocale;
	
	private boolean remmeber;
	private String rmbAcc;
	private String rmbPwd;
	private String pwdPeusdo;
	private int locale;
	private ImageIcon[] imagesLocale = new ImageIcon[2];
	public static Vector<UserAuthorization> listAuthorization;
	
	
	//    HAM TAO CHI CHINH THONG SO KT(DAI-RONG...) VA TITLE
	//    VIET GIAO DIEN TAI initComponents()
    public Login(String rmb, String acc, String pwd, int local){
    	setAlwaysOnTop(true);
    	setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);  	    
  	    setPreferredSize(new Dimension(width, heightMin));
  	    setLocation((screenWidth-width)/2, (screenHeight-heightMax)/2);  	    
  	    Image icon = UtilityGUI.tk.getImage(getClass().getResource("/image/featured.gif"));
	    setIconImage(icon);
  	    setTitle(UtilityGUI.titleLogin);
  	    locale = local;
		if(rmb.equals("1")) remmeber = true;
		else if(rmb.equals("0")) remmeber = false;
  	    if(remmeber){
  	    	rmbAcc = acc;
  	    	rmbPwd = pwd;
  	    	pwdPeusdo = StringUtil.randomPwd(15);
  	    	initComponents(pwdPeusdo);
  	    }else{
  	    	initComponents("");
  	    }
  	    addWindowListener(new WindowEventHandler());
    }
    
    
    
    private void initComponents(String pwd) {

    	GridBagLayout gridBagLayout = new GridBagLayout();
  	    gridBagLayout.columnWidths = new int[]{0, 0};
  	    gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
  	    gridBagLayout.columnWeights = new double[]{0.0, 1.0};
  	    gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0};
  	    getContentPane().setLayout(gridBagLayout);
  	    
  	    lblTitle = new JLabel(UtilityGUI.lblLogin);
  	    lblTitle.setFont(UtilityGUI.fontHeader2);
  	    GridBagConstraints gbc_lblTitle = new GridBagConstraints();
  	    gbc_lblTitle.gridwidth = 2;
  	    gbc_lblTitle.insets = new Insets(10, 10, 3, 10);
  	    gbc_lblTitle.gridx = 0;
  	    gbc_lblTitle.gridy = 0;
  	    getContentPane().add(lblTitle, gbc_lblTitle);
	    
	    imagesLocale[0] = new ImageIcon(getClass().getResource("/image/gb.png"));
	    imagesLocale[1] = new ImageIcon(getClass().getResource("/image/vn.png"));
	    btnLocale = new JButton(imagesLocale[locale]);
	    btnLocale.addActionListener(this);
	    GridBagConstraints gbc_btnLocale = new GridBagConstraints();
	    gbc_btnLocale.anchor = GridBagConstraints.EAST;
	    gbc_btnLocale.insets = new Insets(0, 3, 3, 10);
	    gbc_btnLocale.gridx = 1;
	    gbc_btnLocale.gridy = 1;
	    getContentPane().add(btnLocale, gbc_btnLocale);
  	    
  	    lblUserName = new JLabel(UtilityGUI.lblAcc+" :");
  	    lblUserName.setFont(UtilityGUI.fontLblForm);
  	    GridBagConstraints gbc_lblUserName = new GridBagConstraints();
  	    gbc_lblUserName.anchor = GridBagConstraints.WEST;
  	    gbc_lblUserName.insets = new Insets(3, 10, 5, 5);
  	    gbc_lblUserName.gridx = 0;
  	    gbc_lblUserName.gridy = 2;
  	    getContentPane().add(lblUserName, gbc_lblUserName);
  	    
  	    txtUserName = new JTextField();
  	    txtUserName.setText(rmbAcc);
  	    GridBagConstraints gbc_txtUserName = new GridBagConstraints();
  	    gbc_txtUserName.fill = GridBagConstraints.BOTH;
  	    gbc_txtUserName.insets = new Insets(3, 3, 5, 10);
  	    gbc_txtUserName.gridx = 1;
  	    gbc_txtUserName.gridy = 2;
  	    getContentPane().add(txtUserName, gbc_txtUserName);
  	    
  	    lblUserPass = new JLabel(UtilityGUI.lblPwd+" :");
  	    lblUserPass.setFont(UtilityGUI.fontLblForm);
  	    GridBagConstraints gbc_lblUserPass = new GridBagConstraints();
  	    gbc_lblUserPass.anchor = GridBagConstraints.WEST;
  	    gbc_lblUserPass.insets = new Insets(3, 10, 5, 5);
  	    gbc_lblUserPass.gridx = 0;
  	    gbc_lblUserPass.gridy = 3;
  	    getContentPane().add(lblUserPass, gbc_lblUserPass);
  	    
  	    txtUserPass = new JPasswordField();
  	    txtUserPass.setText(pwd);
  	    GridBagConstraints gbc_txtUserPass = new GridBagConstraints();
  	    gbc_txtUserPass.fill = GridBagConstraints.BOTH;
  	    gbc_txtUserPass.insets = new Insets(3, 3, 5, 10);
  	    gbc_txtUserPass.gridx = 1;
  	    gbc_txtUserPass.gridy = 3;
  	    getContentPane().add(txtUserPass, gbc_txtUserPass);
  	    
  	    cbPass = new JCheckBox(UtilityGUI.btnRememberPwd);
  	    cbPass.setSelected(remmeber);
  	    GridBagConstraints gbc_cbPass = new GridBagConstraints();
  	    gbc_cbPass.anchor = GridBagConstraints.WEST;
  	    gbc_cbPass.insets = new Insets(3, 3, 0, 10);
  	    gbc_cbPass.gridx = 1;
  	    gbc_cbPass.gridy = 4;
  	    getContentPane().add(cbPass, gbc_cbPass);
  	    
  	    panelBtn = new JPanel();
  	    GridBagConstraints gbc_panelBtn = new GridBagConstraints();
  	    gbc_panelBtn.gridwidth = 2;
  	    gbc_panelBtn.insets = new Insets(0, 10, 0, 10);
  	    gbc_panelBtn.fill = GridBagConstraints.BOTH;
  	    gbc_panelBtn.gridx = 0;
  	    gbc_panelBtn.gridy = 5;
  	    getContentPane().add(panelBtn, gbc_panelBtn);
  	    
  	    btnLogin = new JButton(UtilityGUI.btnLog);
  	    btnLogin.setMnemonic(KeyEvent.VK_ENTER);
  	    btnLogin.setFont(UtilityGUI.fontBtnForm);
  	    btnLogin.addActionListener(this);
  	    panelBtn.add(btnLogin);
  	    
  	    btnCancel = new JButton(UtilityGUI.btnCancel);
  	    btnCancel.setFont(UtilityGUI.fontBtnForm);
  	    btnCancel.addActionListener(this);
  	    panelBtn.add(btnCancel);
  	    
  	    cbConfig = new JCheckBox(UtilityGUI.btnConfig);
  	    cbConfig.addActionListener(this);
  	    GridBagConstraints gbc_cbSetUp = new GridBagConstraints();
  	    gbc_cbSetUp.anchor = GridBagConstraints.WEST;
  	    gbc_cbSetUp.gridwidth = 2;
  	    gbc_cbSetUp.insets = new Insets(0, 10, 5, 5);
  	    gbc_cbSetUp.gridx = 0;
  	    gbc_cbSetUp.gridy = 6;
  	    getContentPane().add(cbConfig, gbc_cbSetUp);
  	    
  	    panelConfig = new JPanel();
  	    gbc_panelConfig = new GridBagConstraints();
	    gbc_panelConfig.gridwidth = 2;
	    gbc_panelConfig.insets = new Insets(0, 10, 10, 10);
	    gbc_panelConfig.fill = GridBagConstraints.BOTH;
	    gbc_panelConfig.gridx = 0;
	    gbc_panelConfig.gridy = 7;
	    getContentPane().add(panelConfig, gbc_panelConfig);
	    
	}
    
    private JPanel getPanelConfig(){
    	JPanel panel = new JPanel();  	    
  	    GridBagLayout gbl_panelConfig = new GridBagLayout();
  	    gbl_panelConfig.columnWidths = new int[]{80, 0, 0};
  	    gbl_panelConfig.rowHeights = new int[]{0, 0, 0};
  	    gbl_panelConfig.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
  	    gbl_panelConfig.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
  	    panel.setLayout(gbl_panelConfig);
  	    
  	    lblServer = new JLabel("Server :");
  	    lblServer.setFont(UtilityGUI.fontLblForm);
  	    GridBagConstraints gbc_lblServer = new GridBagConstraints();
  	    gbc_lblServer.insets = new Insets(0, 0, 5, 5);
  	    gbc_lblServer.anchor = GridBagConstraints.WEST;
  	    gbc_lblServer.gridx = 0;
  	    gbc_lblServer.gridy = 0;
  	    panel.add(lblServer, gbc_lblServer);
  	    
  	    txtServer = new JTextField();
  	    GridBagConstraints gbc_txtServer = new GridBagConstraints();
  	    gbc_txtServer.insets = new Insets(0, 0, 5, 0);
  	    gbc_txtServer.fill = GridBagConstraints.BOTH;
  	    gbc_txtServer.gridx = 1;
  	    gbc_txtServer.gridy = 0;
  	    panel.add(txtServer, gbc_txtServer);
  	    
  	    lblPort = new JLabel("Port :");
  	    lblPort.setFont(UtilityGUI.fontLblForm);
  	    GridBagConstraints gbc_lblPort = new GridBagConstraints();
  	    gbc_lblPort.anchor = GridBagConstraints.WEST;
  	    gbc_lblPort.insets = new Insets(3, 0, 5, 5);
  	    gbc_lblPort.gridx = 0;
  	    gbc_lblPort.gridy = 1;
  	    panel.add(lblPort, gbc_lblPort);
  	    
  	    txtPort = new JTextField();
  	    GridBagConstraints gbc_txtPort = new GridBagConstraints();
  	    gbc_txtPort.insets = new Insets(3, 0, 5, 0);
  	    gbc_txtPort.fill = GridBagConstraints.BOTH;
  	    gbc_txtPort.gridx = 1;
  	    gbc_txtPort.gridy = 1;
  	    panel.add(txtPort, gbc_txtPort);
  	    
  	    return panel;
	}
    
    
    public void actionPerformed(ActionEvent e){
    	if(e.getSource() == cbConfig){
    		if(cbConfig.isSelected()){
	    		panelConfig.setVisible(false);
	    		setSize(width, heightMax);
	    		panelConfig = getPanelConfig();
	    		getContentPane().add(panelConfig, gbc_panelConfig);
    		}else{
    			txtServer.setText("");
        		txtPort.setText("");
    			panelConfig.setVisible(false);
    			setSize(width, heightMin);
    			panelConfig = new JPanel();
	    		getContentPane().add(panelConfig, gbc_panelConfig);
    		}
    	}
    	
    	if(e.getSource() == btnLocale){
    		if(locale == 0){
    			dispose();
    			EventQueue.invokeLater(new Runnable() {
    				public void run(){
    					try {
    						//	LOAD XML
    						Vector<String> log;
							log = XMLProcess.readLogin();
							UtilityGUI.setButton(1);
							UtilityGUI.setLbl(1);
							UtilityGUI.setTitle(1);
							UtilityGUI.setToolTip(1);
							UtilityGUI.setMenu(1);
							UtilityGUI.setSubMenu(1);
							UtilityGUI.setTab(1);
							UtilityGUI.setExit(1);
							UtilityGUI.setError(1);
							UtilityGUI.setSuccess(1);
							UtilityGUI.setNotice(1);
							//	LOAD XML
    						Login login = new Login(log.get(0), log.get(1), log.get(2), 1);
    						login.setVisible(true);
    						login.pack();
    					} catch (Exception e) {
    						e.printStackTrace();
    					}
    				}
    			});
    		}else if(locale == 1){
    			dispose();
    			EventQueue.invokeLater(new Runnable() {
    				public void run(){
    					try {
    						//	LOAD XML
    						Vector<String> log;
    						log = XMLProcess.readLogin();
    						UtilityGUI.setButton(0);
    						UtilityGUI.setLbl(0);
    						UtilityGUI.setTitle(0);
    						UtilityGUI.setToolTip(0);
    						UtilityGUI.setMenu(0);
    						UtilityGUI.setSubMenu(0);
    						UtilityGUI.setTab(0);
    						UtilityGUI.setExit(0);
    						UtilityGUI.setError(0);
    						UtilityGUI.setSuccess(0);
    						UtilityGUI.setNotice(0);
    						//	LOAD XML
    						Login login = new Login(log.get(0), log.get(1), log.get(2), 0);
    						login.setVisible(true);
    						login.pack();
    					} catch (Exception e) {
    						e.printStackTrace();
    					}
    				}
    			});
    		}
    	}
    	
        if(e.getSource() == btnLogin){
        	if(txtUserName.getText().isEmpty() || txtUserPass.getText().isEmpty()) return;
        	String editServer = "";
        	String editPort = "";
        	Vector<String> config = XMLProcess.readConfig();
			server = config.get(0);
			port = config.get(1);
			Thread thread = new Thread();
        	Loading loading = new Loading("sao lai ko duoc");
        	try {
        		setVisible(false);
            	loading.open(60000);
				thread.join();
            	if(txtServer != null && txtPort != null){
                	editServer = txtServer.getText();
                	editPort = txtPort.getText();
            	}
            	if(!((editServer.isEmpty() || editServer.equals(server)) 
            			&& (editPort.isEmpty() || editPort.equals(port)))){
            		conn = UtilDelegate.getConnection(editServer, editPort);
            	}else{
            		conn = UtilDelegate.getConnection(server, port);
            	}
            	if(conn == null){
            		loading.close();        		
            		JOptionPane.showMessageDialog(null,UtilityGUI.errorLogServer,
                    		UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
                	setVisible(true);
                	return;
            	}
                String userName = txtUserName.getText();
                String pwd;
                if(remmeber){
                	if(txtUserPass.getText().equals(pwdPeusdo)){
                		pwd = rmbPwd;
                	}else pwd = txtUserPass.getText();
                }else{
                	pwd = txtUserPass.getText();
                }
                String pwdMD5 = MD5.MD5Password(pwd);
                UserDelegate userDelegate = new UserDelegate();
                int check = userDelegate.loginCheck(userName, pwdMD5);            
                if(check == 0){
                	loading.close();
                	JOptionPane.showMessageDialog(null,UtilityGUI.errorLogin1,
                    		UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
                	setVisible(true);
                	return;
                }else if(check == -1){
                	loading.close();
                	JOptionPane.showMessageDialog(null,UtilityGUI.errorLogin2,
                    		UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
                	setVisible(true);
                	return;
                }else if(check == 1){
                	dispose();
                	if(cbPass.isSelected()){
                		XMLProcess.writeLogin(true, userName, pwd);
                	}else{
                		XMLProcess.writeLogin(false, "", "");
                	}
    				listAuthorization = userDelegate.getListAuthorizations(userName);
    				Main.main = new Main(userName);
    				loading.close();
    				Main.main.setVisible(true);
                }
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}        	
        }else if(e.getSource() == btnCancel){
        	if(!cbPass.isSelected()){
        		XMLProcess.writeLogin(false, "", "");
        	}
        	UtilDelegate.closeConnection(conn);
            System.exit(0);
        }
    }
    
    private class WindowEventHandler extends WindowAdapter{
		public void windowClosing(WindowEvent evt) {
			if(!cbPass.isSelected()){
        		XMLProcess.writeLogin(false, "", "");
        	}
			UtilDelegate.closeConnection(conn);
		    System.exit(0);
		}
	}
    
    public static void main(String[] args) {
		final Vector<String> log;
		UtilityGUI.themes();
		final Loading loading = new Loading("-- Max Intelligent Software --");
		loading.open(3000);
		
		//	LOAD XML
		log = XMLProcess.readLogin();
		UtilityGUI.setButton(0);
		UtilityGUI.setLbl(0);
		UtilityGUI.setTitle(0);
		UtilityGUI.setToolTip(0);
		UtilityGUI.setMenu(0);
		UtilityGUI.setSubMenu(0);
		UtilityGUI.setTab(0);
		UtilityGUI.setExit(0);
		UtilityGUI.setError(0);
		UtilityGUI.setSuccess(0);
		UtilityGUI.setNotice(0);
		//	LOAD XML
		
		SwingUtilities.invokeLater(new Runnable() {			
			@Override
			public void run() {
				Login login = new Login(log.get(0), log.get(1), log.get(2), 0);
				loading.close();
				login.setVisible(true);
				login.pack();				
			}
		});
		
	}
}